<?php
/**
 * 消息逻辑层
 * 作者: 王勇程 (laughskydragon@qq.com)
 */

namespace app\common\logic;

use app\common\logic\LogicBase;

class Message extends LogicBase
{
    /**
     * 获取消息列表搜索条件
     * @param array $data 搜索参数
     * @return array
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function getWhere($data = [])
    {
        $where = [];
        
        // 搜索条件：标题、内容
        !empty($data['search_data']) && $where['title|content'] = ['like', '%'.$data['search_data'].'%'];
        
        // 消息类型筛选
        !empty($data['type']) && $where['type'] = $data['type'];
        
        // 消息级别筛选
        !empty($data['level']) && $where['level'] = $data['level'];
        
        // 状态筛选
        isset($data['status']) && $data['status'] !== '' && $where['status'] = $data['status'];
        
        // 用户ID筛选
        !empty($data['user_id']) && $where['user_id'] = $data['user_id'];
        
        // 时间范围筛选
        !empty($data['start_time']) && $where['send_time'] = ['>=', strtotime($data['start_time'])];
        !empty($data['end_time']) && $where['send_time'] = ['<=', strtotime($data['end_time'])];
        
        return $where;
    }

    /**
     * 获取消息模板搜索条件
     * @param array $data 搜索参数
     * @return array
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function getTemplateWhere($data = [])
    {
        $where = [];
        
        // 搜索条件：模板名称、模板代码
        !empty($data['search_data']) && $where['name|template_code'] = ['like', '%'.$data['search_data'].'%'];
        
        // 模板类型筛选
        !empty($data['type']) && $where['type'] = $data['type'];
        
        // 状态筛选
        isset($data['status']) && $data['status'] !== '' && $where['status'] = $data['status'];
        
        return $where;
    }

    /**
     * 获取消息列表
     * @param array $where 查询条件
     * @param mixed $field 查询字段
     * @param string $order 排序
     * @param mixed $paginate 分页
     * @return array
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function getMessageList($where = [], $field = true, $order = 'id desc', $paginate = false)
    {
        return $this->modelMessage->getList($where, $field, $order, $paginate);
    }

    /**
     * 获取消息模板列表
     * @param array $where 查询条件
     * @param mixed $field 查询字段
     * @param string $order 排序
     * @param mixed $paginate 分页
     * @return array
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function getMessageTemplateList($where = [], $field = true, $order = 'id desc', $paginate = false)
    {
        return $this->modelMessageTemplate->getList($where, $field, $order, $paginate);
    }

    /**
     * 发送消息
     */
    public function sendMessage($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        $title = $data['title'] ?? '';
        $content = $data['content'] ?? '';
        $type = $data['type'] ?? 1;
        $level = $data['level'] ?? 1;
        
        if (!$title) {
            return ['code' => 1, 'msg' => '消息标题不能为空', 'data' => []];
        }
        
        if (!$content) {
            return ['code' => 1, 'msg' => '消息内容不能为空', 'data' => []];
        }
        
        $messageData = [
            'user_id' => $userId,
            'title' => $title,
            'content' => $content,
            'type' => $type,
            'level' => $level,
            'extra_data' => $data['extra_data'] ?? [],
            'relation_type' => $data['relation_type'] ?? '',
            'relation_id' => $data['relation_id'] ?? 0,
            'send_time' => $data['send_time'] ?? time(),
            'expire_time' => $data['expire_time'] ?? 0
        ];
        
        $messageId = $this->modelMessage->sendMessage($messageData);
        
        if ($messageId) {
            return ['code' => 0, 'msg' => '消息发送成功', 'data' => ['message_id' => $messageId]];
        } else {
            return ['code' => 1, 'msg' => '消息发送失败', 'data' => []];
        }
    }
    
    /**
     * 批量发送消息
     */
    public function sendBatchMessage($data = [])
    {
        $userIds = $data['user_ids'] ?? [];
        $title = $data['title'] ?? '';
        $content = $data['content'] ?? '';
        
        if (empty($userIds)) {
            return ['code' => 1, 'msg' => '接收用户不能为空', 'data' => []];
        }
        
        if (!$title) {
            return ['code' => 1, 'msg' => '消息标题不能为空', 'data' => []];
        }
        
        if (!$content) {
            return ['code' => 1, 'msg' => '消息内容不能为空', 'data' => []];
        }
        
        $messageData = [
            'title' => $title,
            'content' => $content,
            'type' => $data['type'] ?? 1,
            'level' => $data['level'] ?? 1,
            'extra_data' => $data['extra_data'] ?? [],
            'relation_type' => $data['relation_type'] ?? '',
            'relation_id' => $data['relation_id'] ?? 0,
            'send_time' => $data['send_time'] ?? time(),
            'expire_time' => $data['expire_time'] ?? 0
        ];
        
        $result = $this->modelMessage->sendBatchMessages($userIds, $messageData);
        
        if ($result) {
            return ['code' => 0, 'msg' => '批量消息发送成功', 'data' => []];
        } else {
            return ['code' => 1, 'msg' => '批量消息发送失败', 'data' => []];
        }
    }
    
    /**
     * 使用模板发送消息
     */
    public function sendTemplateMessage($data = [])
    {
        $templateCode = $data['template_code'] ?? '';
        $userId = $data['user_id'] ?? 0;
        $variables = $data['variables'] ?? [];
        
        if (!$templateCode) {
            return ['code' => 1, 'msg' => '模板代码不能为空', 'data' => []];
        }
        
        // 渲染模板
        $templateData = $this->modelMessageTemplate->renderTemplate($templateCode, $variables);
        
        if (!$templateData) {
            return ['code' => 1, 'msg' => '消息模板不存在或已禁用', 'data' => []];
        }
        
        $messageData = [
            'user_id' => $userId,
            'title' => $templateData['title'],
            'content' => $templateData['content'],
            'type' => $templateData['type'],
            'level' => $templateData['level'],
            'extra_data' => $data['extra_data'] ?? [],
            'relation_type' => $data['relation_type'] ?? '',
            'relation_id' => $data['relation_id'] ?? 0,
            'send_time' => $data['send_time'] ?? time(),
            'expire_time' => $data['expire_time'] ?? 0
        ];
        
        return $this->sendMessage($messageData);
    }
    
    /**
     * 批量使用模板发送消息
     */
    public function sendBatchTemplateMessage($data = [])
    {
        $templateCode = $data['template_code'] ?? '';
        $userIds = $data['user_ids'] ?? [];
        $variables = $data['variables'] ?? [];
        
        if (!$templateCode) {
            return ['code' => 1, 'msg' => '模板代码不能为空', 'data' => []];
        }
        
        if (empty($userIds)) {
            return ['code' => 1, 'msg' => '接收用户不能为空', 'data' => []];
        }
        
        // 渲染模板
        $templateData = $this->modelMessageTemplate->renderTemplate($templateCode, $variables);
        
        if (!$templateData) {
            return ['code' => 1, 'msg' => '消息模板不存在或已禁用', 'data' => []];
        }
        
        $messageData = [
            'title' => $templateData['title'],
            'content' => $templateData['content'],
            'type' => $templateData['type'],
            'level' => $templateData['level'],
            'extra_data' => $data['extra_data'] ?? [],
            'relation_type' => $data['relation_type'] ?? '',
            'relation_id' => $data['relation_id'] ?? 0,
            'send_time' => $data['send_time'] ?? time(),
            'expire_time' => $data['expire_time'] ?? 0
        ];
        
        $messageData['user_ids'] = $userIds;
        
        return $this->sendBatchMessage($messageData);
    }
    
    /**
     * 获取用户消息列表
     */
    public function getUserMessages($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        $type = $data['type'] ?? null;
        $isRead = $data['is_read'] ?? null;
        $page = $data['page'] ?? 1;
        $limit = $data['limit'] ?? 20;
        
        if (!$userId) {
            return ['code' => 1, 'msg' => '用户ID不能为空', 'data' => []];
        }
        
        $paginate = ['list_rows' => $limit, 'page' => $page];
        $list = $this->modelMessage->getUserMessages($userId, $type, $isRead, $paginate);
        
        return ['code' => 0, 'msg' => '获取成功', 'data' => $list];
    }
    
    /**
     * 获取用户未读消息数量
     */
    public function getUserUnreadCount($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        $type = $data['type'] ?? null;
        
        if (!$userId) {
            return ['code' => 1, 'msg' => '用户ID不能为空', 'data' => []];
        }
        
        $count = $this->modelMessage->getUserUnreadCount($userId, $type);
        
        return ['code' => 0, 'msg' => '获取成功', 'data' => ['count' => $count]];
    }
    
    /**
     * 标记消息为已读
     */
    public function markAsRead($data = [])
    {
        $messageId = $data['message_id'] ?? 0;
        $userId = $data['user_id'] ?? 0;
        
        if (!$messageId) {
            return ['code' => 1, 'msg' => '消息ID不能为空', 'data' => []];
        }
        
        $result = $this->modelMessage->markAsRead($messageId, $userId);
        
        if ($result) {
            return ['code' => 0, 'msg' => '标记成功', 'data' => []];
        } else {
            return ['code' => 1, 'msg' => '标记失败', 'data' => []];
        }
    }
    
    /**
     * 批量标记消息为已读
     */
    public function markMultipleAsRead($data = [])
    {
        $messageIds = $data['message_ids'] ?? [];
        $userId = $data['user_id'] ?? 0;
        
        if (empty($messageIds)) {
            return ['code' => 1, 'msg' => '消息ID不能为空', 'data' => []];
        }
        
        $result = $this->modelMessage->markMultipleAsRead($messageIds, $userId);
        
        if ($result) {
            return ['code' => 0, 'msg' => '批量标记成功', 'data' => []];
        } else {
            return ['code' => 1, 'msg' => '批量标记失败', 'data' => []];
        }
    }
    
    /**
     * 标记所有消息为已读
     */
    public function markAllAsRead($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        $type = $data['type'] ?? null;
        
        if (!$userId) {
            return ['code' => 1, 'msg' => '用户ID不能为空', 'data' => []];
        }
        
        $result = $this->modelMessage->markAllAsRead($userId, $type);
        
        if ($result) {
            return ['code' => 0, 'msg' => '全部标记成功', 'data' => []];
        } else {
            return ['code' => 1, 'msg' => '全部标记失败', 'data' => []];
        }
    }
    
    /**
     * 删除消息
     */
    public function deleteMessage($data = [])
    {
        $messageId = $data['message_id'] ?? 0;
        $userId = $data['user_id'] ?? 0;
        
        if (!$messageId) {
            return ['code' => 1, 'msg' => '消息ID不能为空', 'data' => []];
        }
        
        $result = $this->modelMessage->deleteMessage($messageId, $userId);
        
        if ($result) {
            return ['code' => 0, 'msg' => '删除成功', 'data' => []];
        } else {
            return ['code' => 1, 'msg' => '删除失败', 'data' => []];
        }
    }
    
    /**
     * 批量删除消息
     */
    public function deleteMultipleMessages($data = [])
    {
        $messageIds = $data['message_ids'] ?? [];
        $userId = $data['user_id'] ?? 0;
        
        if (empty($messageIds)) {
            return ['code' => 1, 'msg' => '消息ID不能为空', 'data' => []];
        }
        
        $result = $this->modelMessage->deleteMultipleMessages($messageIds, $userId);
        
        if ($result) {
            return ['code' => 0, 'msg' => '批量删除成功', 'data' => []];
        } else {
            return ['code' => 1, 'msg' => '批量删除失败', 'data' => []];
        }
    }
    
    /**
     * 清理过期消息
     */
    public function cleanExpiredMessages($data = [])
    {
        $result = $this->modelMessage->cleanExpiredMessages();
        
        if ($result) {
            return ['code' => 0, 'msg' => '清理完成', 'data' => []];
        } else {
            return ['code' => 1, 'msg' => '清理失败', 'data' => []];
        }
    }
    
    /**
     * 获取消息统计
     */
    public function getMessageStatistics($data = [])
    {
        $startTime = $data['start_time'] ?? null;
        $endTime = $data['end_time'] ?? null;
        
        if ($startTime) {
            $startTime = strtotime($startTime);
        }
        
        if ($endTime) {
            $endTime = strtotime($endTime);
        }
        
        $statistics = $this->modelMessage->getMessageStatistics($startTime, $endTime);
        
        return ['code' => 0, 'msg' => '获取成功', 'data' => $statistics];
    }
    
    /**
     * VIP购买成功消息
     */
    public function sendVipOrderSuccessMessage($userId, $orderData)
    {
        $variables = [
            'order_no' => $orderData['order_no'],
            'duration' => $orderData['duration'],
            'amount' => $orderData['amount'],
            'start_time' => date('Y-m-d H:i:s', $orderData['start_time']),
            'end_time' => date('Y-m-d H:i:s', $orderData['end_time'])
        ];
        
        return $this->sendTemplateMessage([
            'template_code' => 'vip_order_success',
            'user_id' => $userId,
            'variables' => $variables,
            'relation_type' => 'vip_order',
            'relation_id' => $orderData['id']
        ]);
    }
    
    /**
     * VIP即将到期提醒
     */
    public function sendVipExpireRemindMessage($userId, $expireTime, $renewUrl = '')
    {
        $variables = [
            'expire_time' => date('Y-m-d H:i:s', $expireTime),
            'renew_url' => $renewUrl
        ];
        
        return $this->sendTemplateMessage([
            'template_code' => 'vip_expire_remind',
            'user_id' => $userId,
            'variables' => $variables,
            'relation_type' => 'vip',
            'relation_id' => $userId
        ]);
    }
    
    /**
     * 提现审核通过消息
     */
    public function sendWithdrawAuditPassMessage($userId, $withdrawData)
    {
        $variables = [
            'amount' => $withdrawData['amount'],
            'fee' => $withdrawData['fee'],
            'actual_amount' => $withdrawData['actual_amount'],
            'apply_time' => date('Y-m-d H:i:s', $withdrawData['apply_time'])
        ];
        
        return $this->sendTemplateMessage([
            'template_code' => 'withdraw_audit_pass',
            'user_id' => $userId,
            'variables' => $variables,
            'relation_type' => 'withdraw',
            'relation_id' => $withdrawData['id']
        ]);
    }
    
    /**
     * 提现申请被拒绝消息
     */
    public function sendWithdrawAuditRejectMessage($userId, $withdrawData, $reason = '')
    {
        $variables = [
            'amount' => $withdrawData['amount'],
            'reason' => $reason ?: '不符合提现要求',
            'apply_time' => date('Y-m-d H:i:s', $withdrawData['apply_time'])
        ];
        
        return $this->sendTemplateMessage([
            'template_code' => 'withdraw_audit_reject',
            'user_id' => $userId,
            'variables' => $variables,
            'relation_type' => 'withdraw',
            'relation_id' => $withdrawData['id']
        ]);
    }
    
    /**
     * 提现成功消息
     */
    public function sendWithdrawSuccessMessage($userId, $withdrawData)
    {
        $variables = [
            'amount' => $withdrawData['amount'],
            'actual_amount' => $withdrawData['actual_amount'],
            'pay_time' => date('Y-m-d H:i:s', $withdrawData['pay_time'])
        ];
        
        return $this->sendTemplateMessage([
            'template_code' => 'withdraw_success',
            'user_id' => $userId,
            'variables' => $variables,
            'relation_type' => 'withdraw',
            'relation_id' => $withdrawData['id']
        ]);
    }
}